package light.head.controller.sys;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import light.head.constant.Msg;
import light.head.constant.Parm;
import light.head.constant.Sys;
import light.head.constant.Url;
import light.head.dao.sys.OrganDAO;
import light.head.dao.sys.PostDAO;
import light.head.dao.sys.RoleDAO;
import light.head.dao.sys.UserInfoDAO;
import light.head.enm.RESULT;
import light.head.framework.base.SupporterController;
import light.head.framework.entity.PageBean;
import light.head.framework.utils.MD5Utils;
import light.head.framework.utils.PinYinUtils;
import light.head.model.Organ;
import light.head.model.Post;
import light.head.model.Role;
import light.head.model.UserInfo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;

/**
 * @author janhang
 * @2011-8-22  下午03:11:00
 * 用户信息管理
 */
@Controller
@RequestMapping(value = Url.C_USER)
public class UserController extends SupporterController {

	private UserInfoDAO userDAO;
	private OrganDAO organDAO;
	private RoleDAO roleDAO;
	private PostDAO pDAO;
	@RequestMapping(value = Url.INIT)
	public ModelAndView init(HttpServletRequest request, HttpServletResponse response) throws Exception {
		return new ModelAndView(Url.USER_INIT);
	}

	@RequestMapping(value = Url.QUERY)
	public ModelAndView query(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pb = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.REAL_NAME, Parm.ISMANAGER, Parm.DELETED, Parm.OC);
		if (userDAO.findByMap(map, pb) == RESULT.SUCCESS)
			request.setAttribute(Parm.PAGE_BEAN, pb);
		
		return new ModelAndView(Url.USER_LIST);
	}

	@RequestMapping(value = Url.EDIT)
	public ModelAndView edit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (isNotNull(code)) {
			UserInfo user = userDAO.get(Integer.parseInt(code));
			List<Role> roles = roleDAO.getAllByOrgCode(user.getOc().toString());
			request.setAttribute("roles", roles);
			request.setAttribute(Parm.USER, user);
		}
		return new ModelAndView(Url.USER_EDIT);
	}

	@RequestMapping(value = Url.EDIT_SELF)
	public ModelAndView editSelf(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Integer cu_code = cu_code(request);
		if (null == cu_code) {
			request.setAttribute(Parm.INFO, Msg.NO_LOGIN);
			return new ModelAndView(Url.BS_LOGIN);
		}
		if (cu_code != null){
			List<Post> p = pDAO.findUc(cu_code(request));
			request.setAttribute(Parm.POST, p);
		}
		UserInfo user = userDAO.get(cu_code);
		request.setAttribute(Parm.USER, user);
		return new ModelAndView(Url.USER_EDIT_SELF);
	}

	@RequestMapping(value = Url.SAVE_SELF)
	public ModelAndView saveSelf(UserInfo user, HttpServletRequest request, HttpServletResponse response) throws Exception {
		Integer cu_code = cu_code(request);
		
		if (null == cu_code) {
			request.setAttribute(Parm.INFO, Msg.NO_LOGIN);
			return new ModelAndView(Url.BS_LOGIN);
		}
		user.setCode(cu_code);
		if (isNotNull(user.getRealName())) {
			user.setPinyin(PinYinUtils.cn2py(user.getRealName()));
			user.setPy(PinYinUtils.cn2first(user.getRealName()));
		}
		if (isNotNull(user.getPwd())) {
			user.setPwd(MD5Utils.encryptTo32(user.getPwd()));
		}
		if (userDAO.update(user) == RESULT.SUCCESS) 
			print(response, Msg.SUCCESS);
		else 
			print(response, Msg.ERROR);
		
		return null;
	}
	
	@RequestMapping(value = Url.SAVE)
	public void save(UserInfo user, HttpServletRequest request, HttpServletResponse response) throws Exception {
		RESULT result = RESULT.ERROR;
		
		// 验证  email 是否重复
		if (!userDAO.checkEmail(user.getEmail(), user.getCode())) {
			print(response, Msg.EXISTS);
			return;
		}
		// 判断是否选择用户所属公司，如果未选择就不能进行正常操作
		if (user.getOc() == null) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		
		if (isNotNull(user.getRealName())) {
			user.setPinyin(PinYinUtils.cn2py(user.getRealName()));
			user.setPy(PinYinUtils.cn2first(user.getRealName()));
		}
		
		if (null != user.getCode())  {
			result = userDAO.update(user);
		} else {
			user.setCt(new Date());
			user.setPwd(Sys.DEFAULT_PWD);
			result = userDAO.add(user);
		}
		
		if (RESULT.SUCCESS == result) {
			if (user.getRc() == null && (user.getIsManager() == null || !user.getIsManager()))
				print(response, Msg.NO_ANY_RIGHTS);
			else
				print(response, Msg.SUCCESS);
		} else 
			print(response, Msg.ERROR);
	}
	
	@RequestMapping(value = Url.DELETE)
	public void delete(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (!isNotNull(code)) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		
		if (userDAO.del(Integer.parseInt(code)) == RESULT.SUCCESS)
			print(response, Msg.SUCCESS);
		else 
			print(response, Msg.ERROR);
	}
	
	@RequestMapping(value = Url.SHIELD)
	public void shield(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (!isNotNull(code)) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		UserInfo user = userDAO.get(Integer.parseInt(code));
		if (null == user) {
			print(response, Msg.NOT_FIND);
			return;
		}

		user.setDeleted(true);
		if (userDAO.upd(user) == RESULT.SUCCESS)
			print(response, Msg.SUCCESS);
		else
			print(response, Msg.ERROR);
	}
	
	@RequestMapping(value = Url.UN_SHIELD)
	public void unshield(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (!isNotNull(code)) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		UserInfo user = userDAO.get(Integer.parseInt(code));
		if (null == user) {
			print(response, Msg.NOT_FIND);
			return;
		}
			
		user.setDeleted(false);
		if (userDAO.upd(user) == RESULT.SUCCESS)
			print(response, Msg.SUCCESS);
		else
			print(response, Msg.ERROR);
	}
	
	@RequestMapping(value = Url.UPDATE_PWD)
	public void updatePwd(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String oldpwd = request.getParameter("oldpwd");
		String newpwd = request.getParameter("newpwd");
		if (null == oldpwd || null == newpwd || newpwd.length() < 6) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		UserInfo user = userDAO.getByEmail(cu_email(request));
		
		if (null == user) {
			print(response, Msg.NOT_FIND);
			return;
		}
		if (!MD5Utils.encryptTo32(oldpwd).equals(user.getPwd())) {
			print(response, Msg.PWD_ERROR);
			return;
		}
		user.setPwd(MD5Utils.encryptTo32(newpwd));
		if (userDAO.upd(user) == RESULT.SUCCESS)
			print(response, Msg.SUCCESS);
		else 
			print(response, Msg.ERROR);
	}
	
	@RequestMapping(value = Url.UPDATE_PAGE_STYLE)
	public void updatePageStyle(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String pageStyle = request.getParameter(Parm.PAGE_STYLE);
		
		if (null == pageStyle || Sys.NONE.equals(pageStyle)) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		
		UserInfo user = userDAO.get(cu_code(request));
		if (null == user) {
			print(response, Msg.NOT_FIND);
			return;
		}
		
		user.setPageStyle(pageStyle);
		if (userDAO.upd(user) == RESULT.SUCCESS) {
			request.getSession().setAttribute(Parm.CU_PAGE_STYLE, pageStyle);
			print(response, Msg.SUCCESS);
		} else {
			print(response, Msg.FAILURE);
		}
	}
	
	@RequestMapping(Url.AID_INIT)
	public ModelAndView aidQueryList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		List<Organ> list = organDAO.getAll();
 		if (null != list) {
			StringBuffer tree = new StringBuffer();
			for (Organ o : list) {
				if (!o.getDeleted()) {
					tree.append("p.add('" + o.getCode() + "','-1','"+ o.getName() + "');");
					aidTree(tree, o.getSonList());
				}
			}
			request.setAttribute(Parm.TREE, tree);
			request.setAttribute(Parm.ORGAN, list);
		}
 		request.setAttribute(Parm.ID, request.getParameter(Parm.ID));
		request.setAttribute(Parm.NAME, request.getParameter(Parm.NAME));
		return new ModelAndView(Url.USER_AID_INIT);
	}
	
	
	private void aidTree(StringBuffer tree, List<Organ> list) {
		if (null == tree || null == list || list.size() == 0)
			return;
		for (Organ o : list) {
			if (!o.getDeleted()) {
				tree.append("p.add('" + o.getCode() + "','" + o.getPc() + "','" + o.getName() + "');");
				aidTree(tree, o.getSonList());
			}
		}
	}
	
	@RequestMapping(Url.CHANGE_ROLE)
	public void changeRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String strOc = request.getParameter(Parm.OC);
		List<Role> roles = roleDAO.getAllByOrgCode(strOc);
		response.setContentType("application/json;charset=utf-8");
		Gson gson = new Gson();
		String json = gson.toJson(roles);
		response.getWriter().write(json);
	}
	
	
	@Autowired
	public void setOrganDAO(OrganDAO organDAO) {
		this.organDAO = organDAO;
	}

	@Autowired
	public void setUserDAO(UserInfoDAO userDAO) {
		this.userDAO = userDAO;
	}

	@Autowired
	public void setRoleDAO(RoleDAO roleDAO) {
		this.roleDAO = roleDAO;
	}
	@Autowired
	public void setpDAO(PostDAO pDAO) {
		this.pDAO = pDAO;
	}
	
}
